package sbc.group1.lab1.mozartspaces;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;

import org.mozartspaces.capi3.AnyCoordinator;
import org.mozartspaces.core.MzsCoreException;
import org.mozartspaces.core.MzsConstants.RequestTimeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.misc.Signal;
import sun.misc.SignalHandler;

public class NotifyOn2000FinishedCars {
    private static final Logger log = LoggerFactory.getLogger(NotifyOn2000FinishedCars.class);
    private final Space space;
    
    public static void main(String args[]) throws MalformedURLException, MzsCoreException, URISyntaxException {
        SpaceClient space = new SpaceClient();
        final Thread t = Thread.currentThread();
        Signal.handle(new Signal("INT"), 
                new SignalHandler() {
                    @Override
                    public void handle(Signal sig) {
                        t.interrupt();
                    }
                });
        Signal.handle(new Signal("HUP"), 
                new SignalHandler() {
                    @Override
                    public void handle(Signal sig) {
                    }
                });
        try {
            space.init(new File(args[0]).toURI().toURL(), new URI(args[1]));
            new NotifyOn2000FinishedCars(space).run();
        }finally {
            space.getCore().shutdown(false);
        }
    }
    
    public NotifyOn2000FinishedCars(Space space) {
        this.space = space;
    }
    
    public void run() {
        try {
            log.info("Cars finished: "+
                    Integer.toString(space.getCapi().test(
                            space.getFinishedCarContainer(), 
                    AnyCoordinator.newSelector(2000), 
                    RequestTimeout.INFINITE, null)));
            
        } catch (MzsCoreException e) {
            log.error("",e);
        }
        
    }
}
